package com.zzh.tree;

import java.util.*;

public class No102_levelOrder {
    public static void main(String[] args) {
        No102Solution solution = new No102Solution();
        List<List<Integer>> lists = solution.levelOrder(TreeNode.initTree());
        for (List<Integer> i:lists){
            System.out.println(Arrays.toString(i.toArray()));
        }
    }
}
//层序遍历，广度优先搜索
class No102Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root==null){
            return new ArrayList<>();
        }
        List<List<Integer>> lists = new ArrayList<>();
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while (!q.isEmpty()) {
            int sz = q.size();//因为队列q是会被动态放入值，所以用原先的size来判断循环结束
            List<Integer> temp = new ArrayList<>();
            for (int i = 0; i < sz; i++) {
                TreeNode cur=q.poll();
                assert cur!=null;
//                System.out.println(cur.val);
                temp.add(cur.val);
                if (cur.left!=null){
                    q.offer(cur.left);
                }
                if (cur.right!=null){
                    q.offer(cur.right);
                }

            }
            lists.add(temp);
        }
        return lists;
    }
}
